package com.garlic.face.jlf.presenter;


import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.ServiceInterface;
import com.garlic.face.jlf.transaction.bean.SaleFlow;
import com.garlic.face.jlf.transaction.constances.JLFConstant;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shiyanqi on 18/9/19.
 */

public class SuperVisorConfirmGoodsPresenter implements SuperVisorConfirmGoodsContract.Presenter {

	SuperVisorConfirmGoodsContract.View mView;
	private static String TAG = "SuperVisorConfirmGoodsPresenter";
	private int reduceOrDelete = -1;//记录是否删除或-1
	String mBarcode;//当前条码
	boolean changePosition = true;//+-不改变列表商品位置

	public SuperVisorConfirmGoodsPresenter(SuperVisorConfirmGoodsContract.View view) {
		mView = view;
	}


	@Override
	public void cancelTransaction() {
		ServiceInterface.getInstance().cancelTrade("", "");
	}

	@Override
	public void getItemInfo(String barCode, String qty) {
		LogUtils.d(TAG + "barCode" + barCode, true);
		ArrayList<SaleFlow> goodsList = Means.getInstance().getItemHead();
		for(SaleFlow item : goodsList){
			if(item.getBarcode().equals(barCode) && item.getPlutype().equals("1") && !(item.getWeightPluType() == 2)){
				ToastUtils.toastShow("称重商品不可重复扫码", ToastUtils.ERROR);
				return;
			}

		}
		mView.showProgress();
		mBarcode = barCode;
		ServiceInterface.getInstance().getGoodsInfo(mBarcode, qty);
	}

	@Override
	public void addItem(int position) {
		changePosition = false;
		SaleFlow selectItem = getItemList().get(position);

		String barCode = selectItem.getBarcode();
		getItemInfo(barCode, "1");
	}

	@Override
	public void reduceItem(int position) {
		changePosition = false;
		reduceOrDelete = 1;
		Means.getInstance().setPosition(position);
		final SaleFlow saleFlow = getItemList().get(position);
		ServiceInterface.getInstance().removeBarcode("", "", saleFlow.getBarcode(), "1");
	}

	@Override
	public void removeItem(int position) {
		reduceOrDelete = 0;
		Means.getInstance().setPosition(position);
		//取消单品不需要送supervisor
		final SaleFlow saleFlow = getItemList().get(position);
		ServiceInterface.getInstance().removeBarcode("", "", saleFlow.getBarcode(), String.valueOf(saleFlow.getCount()));
	}

	public List<SaleFlow> getItemList() {
		return Means.getInstance().getItemHead();
	}

	@Override
	public void parseResponse(JSONObject jsonObject) {
		try {
			String interfaceType = jsonObject.getString("INTERFACETYPE");
			String retflag = jsonObject.getString("retflag");
			String retmsg = jsonObject.getString("retmsg");

			if (interfaceType.equals(JLFConstant.TAG_GOOD_RESPONSE)) {
				mView.hideProgress();
				if (retflag.equals("0")) {
					SaleFlow saleFlow = new SaleFlow();
					saleFlow.setBarcode(mBarcode);
					fillSaleFlow(saleFlow, jsonObject);
					int count = Means.getInstance().getItemCount();
					Means.getInstance().setItemCount(count + 1);

					calcItemList(saleFlow);//合并或添加商品
					setTotalData();
					//mView.showItemDialog(true, saleFlow, Means.getInstance().getRec_Tran());
					mView.processItemList();
//                    mView.setCurrentSaleFlow(saleFlow);
				} else {
					ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
					LogUtils.e("添加商品" + retmsg);
				}
			} else if (interfaceType.equals(JLFConstant.TAG_CANCELGOOD_RESPONSE)) {
				mView.hideProgress();
//                mView.setCurrentSaleFlow(Means.getInstance().getItemHead().get(Means.getInstance().getPosition()));
				if (retflag.equals("0")) {
					if (reduceOrDelete == 0) {
						Means.getInstance().getItemHead().remove(Means.getInstance().getPosition());
					} else if (reduceOrDelete == 1) {
						SaleFlow saleFlow = Means.getInstance().getItemHead().get(Means.getInstance().getPosition());
						int count = saleFlow.getCount();
						count = count - 1;
						saleFlow.setCount(count);
					}
					setTotalData();
					mView.processItemList();
				} else {
					ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
					LogUtils.e("取消商品" + retmsg);
				}
				reduceOrDelete = -1;
			} else if (interfaceType.equals(JLFConstant.TAG_CANCELTRADE_RESPONSE)) {
				mView.hideProgress();
				if (retflag.equals("0")) {
					Tools.clearTrade();
					mView.processItemList();
					mView.gotoMain();
				} else {
					ToastUtils.toastShow(retmsg, ToastUtils.ERROR);
					LogUtils.e("取消交易" + retmsg);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void fillSaleFlow(SaleFlow saleFlow, JSONObject jsonObject) {
		ArrayList<SaleFlow> goodsList = Means.getInstance().getItemHead();
		try {
			for (SaleFlow item : goodsList) {
				if (item.getBarcode().equals(saleFlow.getBarcode())) {
					saleFlow.setAmount(jsonObject.getDouble("amount"));
					saleFlow.setDisc(100);
					saleFlow.setDiscAmt(item.getDiscAmt());
					saleFlow.setDisctype("");
					saleFlow.setErpLinenmbr(item.getErpLinenmbr());
					saleFlow.setExpectweight(item.getExpectweight());
					saleFlow.setFlowid(item.getFlowid());
					saleFlow.setFname(item.getFname());
					saleFlow.setIncode(item.getIncode());
					saleFlow.setWeight(item.getWeight());
					saleFlow.setPlutype(item.getPlutype());
					saleFlow.setUnitprice(item.getUnitprice());
					saleFlow.setQty(item.getQty());
					saleFlow.setPrice(item.getPrice());
					if (!saleFlow.getPlutype().equals("3")) {
						saleFlow.setCount(1);
					}
					saleFlow.setSpecs("");
					saleFlow.setUnit("");
					return;
				}
			}
			saleFlow.setAmount(jsonObject.getDouble("amount"));
			saleFlow.setDisc(100);
			saleFlow.setDiscAmt(jsonObject.getDouble("linedisc"));
			saleFlow.setDisctype("");
			saleFlow.setErpLinenmbr(jsonObject.getInt("linenmbr"));
			saleFlow.setExpectweight(jsonObject.getDouble("weight"));
			saleFlow.setFlowid(jsonObject.getInt("linenmbr"));
			saleFlow.setFname(jsonObject.getString("desc"));
			saleFlow.setIncode(jsonObject.getString("itemnmbr"));
			// TODO: 2018/7/24 商品类型
			String plutype = jsonObject.getString("plutype");//0-普通，1-称重，2-计数
			Double weight = jsonObject.getDouble("weight");
			Double qty = jsonObject.getDouble("qtysold");
			saleFlow.setWeight(weight);
			saleFlow.setQty(qty);
//            if (plutype.equals("1") && (weight == 1.000 || weight == 1000)) {
//                saleFlow.setPlutype("2");
//            } else {
			saleFlow.setPlutype(plutype);
//            }
			saleFlow.setUnitprice(jsonObject.getDouble("unitprice"));
//			saleFlow.setPrice(saleFlow.getAmount());
			if (saleFlow.getPlutype().equals("0")) {
				saleFlow.setPrice(saleFlow.getAmount());
			} else {
				if (saleFlow.getWeightPluType() == 2) {
					saleFlow.setPrice(saleFlow.getAmount());
				} else {
					saleFlow.setPrice(saleFlow.getAmount());
				}
			}
			saleFlow.setQty(jsonObject.getDouble("qtysold"));
			saleFlow.setSpecs("");
			saleFlow.setUnit("");
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 更新扫描出来的商品到列表顶部，并计算数量是否需要累加
	 *
	 * @param saleFlow
	 */
	private void calcItemList(final SaleFlow saleFlow) {
		//把新扫描到的商品添加到缓存的商品列表中..
		//非承重的逻辑
		LogUtils.d("xxxxx  saleFlow:" + saleFlow, true);
		int index = -1;
		for (int i = 0; i < getItemList().size(); i++) {
			SaleFlow x = getItemList().get(i);
			//手动输入的条码没有开头字母，扫描的带开头字母，这里去除开头字母后匹配
			if (x.getBarcode().replaceAll("^[a-zA-Z]", "").equals(saleFlow.getBarcode().replaceAll("^[a-zA-Z]", ""))) {
				index = i;
				break;
			}
		}

		if (index == -1) {
			//不存在相同的商品..加到顶部
			getItemList().add(0, saleFlow);
		} else {
			//存在相同的商品..
			SaleFlow x = getItemList().get(index);
			//数量+1
			//设置进去
			saleFlow.setCount(x.getCount() + 1);
			int pos = index;
			if (changePosition) {
				pos = 0;
			}
			getItemList().remove(index);
			//归位到顶部
			getItemList().add(pos, saleFlow);
			changePosition = true;
		}

	}

	/**
	 * 设置全局金额、数量
	 */
	private void setTotalData() {
		ArrayList<SaleFlow> goodlist = Means.getInstance().getItemHead();
		Double totalPrice = 0.00;
		Double totalNumber = 0.00;
		Double totalCount = 0.00;
		Double totalWeight = 0.00;
		for (int i = 0; i < goodlist.size(); i++) {
			SaleFlow saleFlow = goodlist.get(i);
			if (saleFlow.getPlutype().equals("0")) {
				totalNumber += saleFlow.getCount();
			} else {
				if (saleFlow.getWeightPluType() == 2) {
					totalNumber += saleFlow.getCount() * saleFlow.getQty();
				} else {
					totalNumber += saleFlow.getQty();
				}
			}
			LogUtils.d("total: totalNumber" + totalNumber + "  saleFlow.getQty():" +
					saleFlow.getQty() + "salefow weight" + saleFlow.getWeight(), true);
			totalWeight += saleFlow.getWeight() * saleFlow.getCount();
			totalCount += saleFlow.getCount();
			totalPrice += (saleFlow.getPrice() * saleFlow.getCount());
		}
		Means.getInstance().getRec_Tran().setAmount(totalPrice);
		Means.getInstance().getRec_Tran().setQty(totalNumber);
		Means.getInstance().getRec_Tran().setCount(totalCount);
		Means.getInstance().getRec_Tran().setWeight(totalWeight);
		LogUtils.d("xxxxx total:" + Means.getInstance().getRec_Tran(), true);
		//这里把预期重量重新设置下
		double weight = 0;
		for (int i = 0; i < Means.getInstance().getItemHead().size(); i++) {
			SaleFlow item = Means.getInstance().getItemHead().get(i);
			if (item.getPlutype().equals("0")) {
				weight += item.getWeight() * item.getCount();
			} else {
				if (item.getWeightPluType() == 2) {
					weight += item.getWeight() * item.getCount() * item.getQty();
				} else {
					weight += item.getWeight() * item.getCount();
				}
			}
			LogUtils.d("xxxxx item.count:" + item.getCount() + "item.weight" + item.getWeight(), true);
		}
		weight = BigDecimal.valueOf(weight).add(BigDecimal.valueOf(Means.BagWeight)).doubleValue();
		LogUtils.e("期望总重量 weight:" + weight );
		Means.TotalWeight = weight;
	}
}
